package main

import (
	"flag"
	"log"
	"math/rand"
	"path"
	"path/filepath"
	"strconv"
	"strings"
	"studygo/other/picutils"
	"sync"
	"time"
)

func init() {
	// 我们一般使用系统时间的不确定性来进行初始化
	rand.Seed(time.Now().UnixNano())
	log.SetPrefix("TRACE: ")
	log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
}

var (
	wg sync.WaitGroup
)

func chanDemo() {
	picChan := make(chan string, 50)
	go func() {
		for i := 0; i < 120; i++ {
			log.Println(i)
			picChan <- strconv.Itoa(i)
		}
		close(picChan)
	}()

	downFromChan(picChan)
	wg.Wait()
}

func downFromChan(picChan chan string) {
	for {
		if data, ok := <-picChan; ok {
			wg.Add(1)
			go func(dat string) {
				defer wg.Done()
				log.Println("取出", dat)
				time.Sleep(2 * time.Second)
			}(data)
		} else {
			break
		}
	}
}
func main() {
	picPath := flag.String("path", "C:/迅雷下载", "文件位置")
	flag.Parse()
	//控制并发，一次执行三个 线程
	files, _ := picutils.GetAllFiles(*picPath)
	myChan := make(chan string, 5)
	//控制并发数
	finishedChan := make(chan string, 5)
	go func() {
		for _, file := range files {
			if picutils.GetFileSize(file) > 1024*1024*100 && (strings.Index(".mp4.m4v.TS", path.Ext(file)) >= 0) {
				slash := filepath.FromSlash(file)
				log.Println("deal with ", slash)
				myChan <- slash
				finishedChan <- slash
			}
		}
		close(myChan)
		close(finishedChan)
	}()
	func(picChan chan string) {
		for {
			if data, ok := <-picChan; ok {
				wg.Add(1)
				go func(filePath string) {
					defer wg.Done()
					//log.Println("==>", file)
					dir, _ := filepath.Split(filePath)
					time.Sleep(time.Second * 2)
					picutils.ExecuteCmdOther("ffmpeg", "-i", filePath, "-y", "-ss", "00:07", "-f", "image2", "-r", "0.003", filepath.FromSlash(dir)+"screenshot_%02d.jpg")
					//picutils.ExecuteCmdOther("ffmpeg", "-i", filePath, "-ss", "03:00", "-f", "image2", "-r", "0.008", "-t", "10:00", dir+"/PIC_%02d.jpg")
					log.Println("完成 ", filePath)
					<-finishedChan
				}(data)
			} else {
				break
			}
		}
	}(myChan)

	// 获取文件，并输出它们的名字
	wg.Wait()
	log.Println("finished")
}
